package org.example.backend.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源映射，用于商品图片访问
        // 将/upload/**请求映射到classpath:/static/upload/目录下
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("classpath:/static/upload/")
                .setCachePeriod(3600)
                .resourceChain(false);
        
        // 添加API路径映射，确保/api/upload/路径也能访问到图片
        registry.addResourceHandler("/api/upload/**")
                .addResourceLocations("classpath:/static/upload/")
                .setCachePeriod(3600)
                .resourceChain(false);
                
        // 同时支持外部文件系统的图片访问
        // 这里使用绝对路径，确保在不同操作系统下都能正常工作
        String uploadPath = System.getProperty("user.dir") + "/upload/";
        registry.addResourceHandler("/external-upload/**")
                .addResourceLocations("file:" + uploadPath);
    }
} 